<template>
  <div class="chat-box">
    <div class="header">聊天室人数:{{count}}</div>
<!--    <scroll class="message" ref="scorll" :data="list">-->
<!--      <div>-->
<!--        <div class="msg-box" ref="msgbox" v-for="(item,index) in list" :key="index">-->
<!--          <span>{{item.content}}</span>-->
<!--          <div class="header-avtor"></div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </scroll>-->
    <div class="bottom">
      <div class="down">
        <el-input type="text" ref="sendMsg" v-model="contentText" />
        <el-button ref="btn" @click="sendText">发送</el-button>
      </div>
    </div>
    <div class="msg-box" ref="msgbox" v-for="(item,index) in list" :key="index">
      <span>{{item.userName}}---{{item.userId}}</span>
      <span>*************</span>
      <span>【{{item.text}}】</span>
      <span>*************</span>
      <span>{{item.date}}</span>
      <div class="header-avtor"></div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'Chat',
  computed: {
    ...mapGetters([
      'name',
      'userId'
    ])
  },
  data() {
    return {
      count: 0,
      msg: '',
      ws: null,
      list: [],
      contentText: ''
    }
  },
  created() {
    this.initWebSocket()
  },
  methods: {
    // 发送聊天消息
    sendText () {
      const that = this
      that.$refs.sendMsg.focus()
      if (!that.contentText) {
        return false
      }
      const params = {
        userId: that.userId,
        userName: that.name,
        text: that.contentText
      }
      if (that.ws.readyState === 1) {
        that.ws.send(JSON.stringify(params)) // 调用WebSocket send()发送信息的方法
      }

      that.contentText = ''
    },
    initWebSocket() {
      const that = this
      // 判断页面有没有存在websocket连接
      if (window.WebSocket) {
        const ws = new WebSocket('ws://8.133.163.121:8089/webSocket/' + that.name)
        that.ws = ws
        ws.onopen = function(e) {
          console.log('服务器连接成功')
        }
        ws.onclose = function(e) {
          console.log('服务器连接关闭')
        }
        ws.onerror = function() {
          console.log('服务器连接出错')
        }
        ws.onmessage = function(e) {
          that.msg = e.data
          console.info('接收服务器返回的数据', e.data)
          // 接收服务器返回的数据
          const resData = JSON.parse(e.data)
          that.count = resData.userCount
          that.list.push(resData)
          // if (resData.funName === 'userCount') {
          //   that.count = resData.users
          //   that.list = resData.chat
          //   console.log(resData.chat)
          // } else {
          //   that.list = [
          //     ...that.list,
          //     { userId: resData.userId, content: resData.msg }
          //   ]
          // }
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
